#include "CString.h"
#include "WinToLinux.h"
#include <string.h>
#include <stdlib.h>

// CString的析构函数  
CString::~CString(void)
{
	delete [] m_data;
}

// CString的普通构造函
CString::CString(char *str)
{  
    if(str == NULL)                            
    {   
        m_data = new char[1];
        *m_data = '\0';
    }
    else  
    {
        int length = strlen(str);
        m_data = new char[length+1];
        strcpy(m_data, str);
    }
}

CString::CString(const char *str)
{  
    if(str == NULL)                            
    {   
        m_data = new char[1];
        *m_data = '\0';
    }
    else  
    {
        int length = strlen(str);
        m_data = new char[length+1];
        strcpy(m_data, str);
    }
}

// 拷贝构造函数  
CString::CString(const CString &other)
{   
    int length = strlen(other.m_data); 
    m_data = new char[length+1];
    strcpy(m_data, other.m_data);
}

// 赋值函数  
CString & CString::operator =(const CString &other)
{
    if(this == &other)
        return *this;

    delete [] m_data;
    int length = strlen(other.m_data);
    m_data = new char[length+1];
    strcpy(m_data, other.m_data);
    return *this; 
}
 
CString & CString::operator =(const char *other)
{
    if(!strcmp(m_data, other))
        return *this;

    delete [] m_data;
    int length = strlen(other);
    m_data = new char[length+1];
    strcpy(m_data, other);
    return *this; 
}
 
CString & CString::operator =(char *other)
{
    if(!strcmp(m_data, other))
        return *this;

    delete [] m_data;
    int length = strlen(other);
    m_data = new char[length+1];
    strcpy(m_data, other);
    return *this; 
}

BOOL CString::operator==( const CString &right ) const
{ 
   return strcmp(m_data, right.m_data) == 0; 
}

char * CString::GetString()const
{
	return m_data;
}

BOOL CString::IsEmpty()const
{
	if (strlen(m_data) == 1) {
		if (*m_data == '\0')
			return 1;
	}
	return 0;
}

int CString::GetLength()const
{
	return strlen(m_data);
}

int CString::Compare(const char * str)const
{
	// only consider ==
	return strcmp(m_data, str);
}

CString CString::Left(int nCount)const
{
	return "Left";
}

CString CString::Right(int nCount)const
{
	return "Right ";
}

// all character are included in lpszCharSet, return 1
int CString::SpanIncluding(LPCTSTR lpszCharSet)const
{
    int len = strlen(lpszCharSet);
    int len_src = strlen(m_data);
	int i = 0, j = 0;
    for (i = 0; i < len_src; ++i) {
        for (j = 0; j < len; ++j) {
            if (*(m_data + i) != *(lpszCharSet + j))
                continue;
            else 
                break;
        }
        if (j == len) {
            return 0;
        }
    }
    return 1;
}

int _ttoi(CString str)
{
	return atoi(str.GetString());
}

